package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        // TODO: [222024321072009/郑子寒] 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            // TODO: [222024321072009/郑子寒] 如果连DefaultHandler都没有，返回500 Internal Server Error
            try{
                String errorResponse = "HTTP/1.1 500 Internal Server Error\r\n" +
                        "Content-Type: text/plain\r\n" +
                        "\r\n" +
                        "500 Internal Server Error: No handler configured";
                response.write(errorResponse.getBytes());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}